﻿using System;
using System.Web;
using Microsoft.SharePoint;

namespace Redirection
{
    public class RedirectionModule
        : IHttpModule
    {
        #region IHttpModule Methods

        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequestHandler;
        }

        public void Dispose()
        {
        }

        #endregion

        private void BeginRequestHandler(object sender, EventArgs eventArgs)
        {
            var application = sender as HttpApplication;
            if (application == null) throw new ArgumentException("Application cannot be null");

            if (application.Context.Request.Url.AbsolutePath.ToLower().Contains("owssvr.dll")) return;

            var site = new SPSite(application.Context.Request.Url.ToString());

            IRedirectionService redirectionService = new RedirectionService(site,application.Context);

            if (redirectionService.RedirectionIsActivated &&
                redirectionService.RequiresRedirect(HttpContext.Current.Request))
            {
                redirectionService.Redirect();
            }
        }
    }
}